import { Router } from 'vue-router'
import { useUserStore } from '@/stores/user'

const whiteList = ['/login', '/404', '/403']

export function setupRouterGuard(router: Router) {
  router.beforeEach(async (to, from, next) => {
    const userStore = useUserStore()

    // 白名单直接放行
    if (whiteList.includes(to.path)) {
      next()
      return
    }

    // 检查是否登录
    if (!userStore.token) {
      next(`/login?redirect=${to.path}`)
      return
    }

    // 获取用户信息
    if (!userStore.userInfo) {
      try {
        await userStore.getUserInfo()
      } catch (error) {
        userStore.logout()
        next(`/login?redirect=${to.path}`)
        return
      }
    }

    // 检查权限
    const requiredRole = to.meta.role
    if (requiredRole && userStore.userInfo?.role !== requiredRole) {
      next('/403')
      return
    }

    next()
  })
}
